nowPage = 1
totalPage = 1
modalInstance = null

class window.UploadModal
  constructor: (@modal) ->
    return modalInstance if modalInstance
    modalInstance = this

  show: ->
    __this = this
    @$gallery = $('#gallery')
    @$galleryContainer = $('#gallery-container')
    @modal
      .on('click', '#btn-upload', @ready4up(__this))
      .on('click', '#refresh-gallery', => @renderGallery(@$galleryContainer.data('page')))
    @modal.on('click', '#gallery-container .check', @selectedCB) if @selectedCB
    @createGallery()
    # 上面的代码初始化，下一次调用 show 不会再次执行
    @show = ->
      $.fn.modal.apply(@modal, arguments)
      this
    @show()

  ready4up: (self) ->
    (e) ->
      e.preventDefault()
      self.fileInput = $('#upload-modal').find('input[type="file"]')
      self.file = file = self.fileInput[0].files[0]
      if (file)
        self.filename = file.name
        reader = new FileReader
        reader.onload = (e) ->
          self.send(reader)
        reader.readAsBinaryString(file)
      else
        ui.dialog('请选择上传图片！').closable().show().hide(2000)

  send: (reader) ->
    self = this
    setTimeout ->
      xhr = new XMLHttpRequest
      $.extend xhr.upload, XhrCB
      data = new FormData
      data.append 'file', self.file
      authToken = self.authToken()
      data.append authToken[0], authToken[1]
      xhr.open('POST', "/backend/attachments", true)
      xhr.send data
    , 0

  authToken: ->
    csrfParam = $("meta[name=csrf-param]").attr('content')
    csrfToken = $("meta[name=csrf-token]").attr('content')
    [csrfParam, csrfToken]

  createGallery: ->
    @$galleryPagination ||= @$gallery.find('ul')
    @galleryInfo (info) ->
      now = 1
      @$galleryPagination.bootstrapPaginator
        currentPage: now
        totalPages: info.total_pages || 1
        bootstrapMajorVersion: 3
        onPageChanged: (e, old, now) =>
          @renderGallery(now)
          @$galleryPagination.data('now', now)
      @renderGallery(now)

  renderGallery: (page) ->
    $.get('/backend/attachments', page: page, per: 12)
    .done (resp) =>
      html = ''
      for attach in resp
        html += @createPreview(attach.id, attach.thumb, attach.url)
      @$galleryContainer.html html

  createPreview: (id, src, big) ->
    """
    <div class="col-sm-4 col-md-4 col-lg-3 image-selector" id="image----selector----#{id}">
      <div class="action">
        <a class="check" href="javascript:void(0);"><i class="fa fa-check"></i></a>
        <a class="times" href="/backend/attachments/#{id}" data-method="delete" data-remote="true" data-confirm="是否删除？"><i class="fa fa-times"></i></a>
      </div>
      <img data-big="#{big}" src="#{src}" alt=""/>
    </div>
    """

  galleryInfo: (cb) ->
    $.get(' /backend/attachments/info')
    .done (resp) =>
        cb.call(this, resp)

  onSelect: (cb) ->
    @selectedCB = cb
    this


XhrCB = {
  onprogress: (event) ->
    if event.lengthComputable
      percentComplete = event.loaded / event.total
      console.log(percentComplete)

  onload: (event) ->
    alert('Ok')
    modalInstance.fileInput.val ''

  onerror: (event) ->
    alert('Error')
    console.log(event)
}